package com.step.ems.pages.wb

import android.net.Uri
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.StringRes
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.Clear
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.SubcomposeAsyncImage
import com.step.ems.R
import com.step.ems.api.WbArea
import com.step.ems.api.WbStatus
import com.step.ems.api.res.WbDetailRes
import com.step.ems.common.PhotoUriManager
import com.step.ems.common.UiState
import com.step.ems.component.ExpandableSection
import com.step.ems.component.ItemInfo
import com.step.ems.component.LoadingBox
import com.step.ems.component.MyTopBar
import com.step.ems.component.TextArea
import com.step.ems.component.TextAreaDisable
import com.step.ems.ui.theme.ContentBg
import com.step.ems.ui.theme.DividerColor

@Composable
fun WbDetailScreen(
    viewModel: WbDetailViewModel = hiltViewModel(),
    gotoItem: (id: Int) -> Unit,
    onPhotoClick: (url: String) -> Unit,
) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    val data by viewModel.data.collectAsStateWithLifecycle()
    val clazz = WbDetailScreenClass(viewModel, data, gotoItem, onPhotoClick)
    Scaffold(topBar = {
        MyTopBar(title = stringResource(R.string.wbDetail)) {
            val btnText = stringResource(id = clazz.getAction(data.maintenanceOrder.maintenanceStatus))
            if (btnText.isNotEmpty()) {
                Text(btnText, modifier = Modifier
                    .clickable { viewModel.changeStatus() }
                    .padding(16.dp))
            }
        }
    }) { padding ->
        LoadingBox(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding), state = state
        ) {
            clazz.Content()
        }
    }
}

class WbDetailScreenClass(
    private val viewModel: WbDetailViewModel,
    private val data: WbDetailRes,
    private val gotoItem: (id: Int) -> Unit,
    private val onPhotoClick: (url: String) -> Unit,
) {
    @Composable
    fun Content() {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
        ) {
            HorizontalDivider(color = ContentBg, thickness = 12.dp)
            if (data.maintenanceOrder.maintenanceStatus == WbStatus.CheckedIn.value) {
                WorkSituationLine(viewModel.workSituationIndex)
                HorizontalDivider(color = DividerColor)
                TextArea(stringResource(R.string.siteSituation), viewModel.description, stringResource(id = R.string.siteNoteTip))
                HorizontalDivider(color = DividerColor)
                PhotoUpload()
            } else if (data.maintenanceOrder.maintenanceStatus > WbStatus.CheckedIn.value!!) {
                WorkSituationLine(viewModel.workSituationIndex, true)
                HorizontalDivider(color = DividerColor)
                TextAreaDisable(stringResource(R.string.siteSituation), viewModel.description.value)
                HorizontalDivider(color = DividerColor)
                PhotoUpload(true)
            }
            HorizontalDivider(color = ContentBg, thickness = 12.dp)
            ExpandableSection(title = stringResource(R.string.ticketInfo), expand = true) {
                Column(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    WbDetailItem(R.string.wbNo, data.maintenanceOrder.maintenanceNo)
                    WbDetailItem(
                        R.string.wbStatus, stringResource(WbStatus.getItem(data.maintenanceOrder.maintenanceStatus)?.titleResId ?: R.string.none)
                    )
                    WbDetailItem(R.string.wbDate, data.maintenanceOrder.maintenanceDate)
                    WbDetailItem(R.string.wbWorker1, data.maintainerOneName)
                    WbDetailItem(R.string.wbWorker2, data.maintainerTwoName)
                    WbDetailItemClickable(R.string.wbItem, "", onClick = { gotoItem(data.maintenanceOrder.maintainerTemplateId) })
                    WbDetailItem(R.string.description, data.maintenanceOrder.description)
                    WbDetailItem(R.string.note, data.maintenanceOrder.note)
                    WbDetailItem(R.string.createTime, data.maintenanceOrder.createDate)
                    WbDetailItem(R.string.updateTime, data.maintenanceOrder.updateDate)
                }
            }
            HorizontalDivider(color = ContentBg, thickness = 12.dp)
            ExpandableSection(title = stringResource(R.string.elevatorInfo), expand = true) {
                Column(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    WbDetailItem(R.string.elevatorNo, data.elevatorView.elevatorVo.registrationCode)
                    WbDetailItem(R.string.elevatorName, data.elevatorView.elevatorVo.name)
                    WbDetailItem(R.string.useUnit, data.elevatorView.elevatorVo.useUnitName)
                    WbDetailItem(R.string.wbUnit, data.elevatorView.elevatorVo.maintenanceCompanyName)
                }
            }
            HorizontalDivider(color = ContentBg, thickness = 12.dp)
        }
    }

    @Composable
    fun WbDetailItem(
        @StringRes titleId: Int,
        value: String,
    ) {
        HorizontalDivider(color = DividerColor)
        ItemInfo(
            titleId,
            value,
            Modifier.padding(horizontal = 18.dp, vertical = 11.dp),
        )
    }

    @Composable
    fun WbDetailItemClickable(
        @StringRes titleId: Int, value: String, onClick: () -> Unit
    ) {
        HorizontalDivider(color = DividerColor)
        ItemInfo(titleId, value,
            Modifier
                .clickable { onClick() }
                .padding(horizontal = 18.dp, vertical = 11.dp), true)
    }

    fun getAction(status: Int): Int {
        return when (status) {
            0 -> R.string.signIn
            1 -> R.string.submit
            else -> R.string.none
        }
    }

    @Composable
    fun WorkSituationLine(workSituationIndex: MutableIntState, disable: Boolean = false) {
        var expanded by remember { mutableStateOf(false) }
        val items = WbArea.entries.toTypedArray()
        Box(modifier = Modifier.background(Color.White)) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable(enabled = !disable) { expanded = true }
                    .padding(horizontal = 15.dp, vertical = 11.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = stringResource(id = R.string.wbArea),
                    fontSize = 16.sp,
                    modifier = Modifier.wrapContentSize(),
                    textAlign = TextAlign.Justify
                )

                var textId = R.string.select
                if (workSituationIndex.intValue != -1) {
                    textId = items[workSituationIndex.intValue].titleResId
                }
                Text(
                    text = stringResource(id = textId),
                    fontSize = 16.sp,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.End,
                    color = Color.Gray
                )
                if (!disable) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Rounded.KeyboardArrowRight,
                        contentDescription = ">",
                        tint = Color.Gray
                    )
                }
            }

            Box(Modifier.align(Alignment.BottomEnd)) {
                DropdownMenu(
                    expanded = expanded,
                    onDismissRequest = { expanded = false },
                    modifier = Modifier
                        .background(Color.White)
                ) {
                    items.forEachIndexed { index, item ->
                        DropdownMenuItem(text = { Text(stringResource(id = item.titleResId)) },
                            onClick = {
                                workSituationIndex.intValue = index
                                expanded = false
                            })
                    }
                }
            }
        }
    }

    @OptIn(ExperimentalLayoutApi::class)
    @Composable
    fun PhotoUpload(disable: Boolean = false) {
        val uiState by viewModel.uploadUiState.collectAsStateWithLifecycle()
        Column(modifier = Modifier.padding(horizontal = 15.dp)) {
            Text(
                text = stringResource(id = R.string.sitePhotos),
                modifier = Modifier
                    .padding(start = 1.dp, top = 10.dp)
                    .fillMaxWidth(),
                fontSize = 16.sp
            )
            FlowRow(
                modifier = Modifier.padding(top = 5.dp, bottom = 16.dp),
            ) {
                viewModel.imageList.forEach { item ->
                    Box(
                        contentAlignment = Alignment.Center
                    ) {
                        SubcomposeAsyncImage(
                            modifier = Modifier
                                .size(80.dp)
                                .padding(5.dp)
                                .clip(RoundedCornerShape(8.dp))
                                .clickable { onPhotoClick(item) },
                            model = item,
                            contentDescription = "Image",
                            contentScale = ContentScale.Crop,
                            loading = {
                                Box(contentAlignment = Alignment.Center) {
                                    CircularProgressIndicator(
                                        modifier = Modifier.size(30.dp),
                                        color = Color.White,
                                        trackColor = Color.Gray,
                                    )
                                }
                            },
                            error = {
                                Box(contentAlignment = Alignment.Center) {
                                    Text(text = stringResource(id = R.string.error))
                                }
                            }
                        )
                        if (!disable) {
                            Box(
                                modifier = Modifier
                                    .size(20.dp)
                                    .clip(CircleShape)
                                    .background(Color.Red)
                                    .align(Alignment.TopEnd)
                                    .clickable { viewModel.imageList.remove(item) },
                                contentAlignment = Alignment.Center
                            ) {
                                Icon(
                                    modifier = Modifier.size(13.dp),
                                    imageVector = Icons.Rounded.Clear,
                                    contentDescription = "x",
                                    tint = Color.White,
                                )
                            }
                        }
                    }
                }

                val photoUriManager = PhotoUriManager(LocalContext.current)
                var newImageUri: Uri? by remember { mutableStateOf(null) }
                val cameraLauncher = rememberLauncherForActivityResult(
                    contract = ActivityResultContracts.TakePicture(),
                    onResult = { success ->
                        if (success) {
                            val imageUri = newImageUri!!
                            Log.d("onPhotoTaken", "拍照成功: $imageUri")
                            viewModel.uploadImage(imageUri)
                        }
                    }
                )

                if (!disable) {
                    val stroke = Stroke(
                        width = 2f,
                        pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
                    )
                    Box(
                        modifier = Modifier
                            .padding(7.dp)
                            .size(66.dp)
                            .drawBehind {
                                drawRoundRect(
                                    color = Color.LightGray,
                                    style = stroke,
                                    cornerRadius = CornerRadius(8.dp.toPx())
                                )
                            }
                            .clickable {
                                newImageUri = photoUriManager.buildNewUri()
                                cameraLauncher.launch(newImageUri!!)
                            },
                        contentAlignment = Alignment.Center,
                    ) {
                        when (uiState) {
                            is UiState.Loading -> {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(30.dp),
                                    color = Color.White,
                                    trackColor = Color.Gray,
                                )
                            }

                            else -> {
                                Icon(
                                    modifier = Modifier.size(30.dp),
                                    imageVector = Icons.Rounded.Add,
                                    contentDescription = "+",
                                    tint = Color.Gray
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}
